package com.lisp.slf4jp.parent_first;

import java.net.URL;
import java.net.URLClassLoader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lisp.slf4jp.box.IBox;

public class RightUse {
	public static void main(String[] args) throws Exception {
		URLClassLoader childClassLoader = new URLClassLoader(
	        new URL[] {
	          new URL("file:lib/slf4j-api-1.7.26.jar"),
	          new URL("file:lib/log4j-1.2.17.jar"),
	          new URL("file:lib/slf4j-log4j12-1.7.26.jar"),
	          new URL("file:lib/"),           // 用于加载log4j.xml
	          new URL("file:target/classes/") // 用于加载com.lisp.clp.box.impl.BoxImpl
        });
		
		Logger logger = LoggerFactory.getLogger(RightUse.class); 
		logger.info("before loading module");
		
		// 设置TCCL并不影响加载过程, 这里可以随意注释掉
		Thread.currentThread().setContextClassLoader(childClassLoader);
		
	    loadModule(childClassLoader);
	    
	    logger.info("after loading module");
	}

	/*
	 * 这里会打印 SLF4J: Class path contains multiple SLF4J bindings
	 * 但其实childClassLoader只能加载到log4j这一个绑定
	 * 误告警的原因是getResources和loadClass的机制有所不同
	 */
	private static void loadModule(URLClassLoader childClassLoader)
			throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Class<?> boxClass = childClassLoader.loadClass("com.lisp.slf4jp.box.impl.BoxImpl");
	    IBox box = (IBox) boxClass.newInstance();
	    box.print();
	}
}
